package myutil;

import java.io.IOException;
import java.sql.*;
import java.util.Map;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Sony
 *
 */

public class Connect extends ActionSupport
{
	public String site;
	public PreparedStatement ps;
	public Connection connection() throws Exception 
	{

		Connection con = null;
		String url = "jdbc:mysql://localhost:3306/"+site;

		// String db = "IE";
		String driver = "com.mysql.jdbc.Driver";
		String user = "root";
		String pass = "root";
				Class.forName(driver).newInstance();
			con = DriverManager.getConnection(url, user, pass);
		

		return con;

	}

	public ResultSet getResult(String query) throws Exception
	{
		// System.out.println(query);
		ResultSet result = null;
		Statement stmt = null;
		Connection con = null;
		
			HttpSession session=ServletActionContext.getRequest().getSession();
			con=(Connection)session.getAttribute("connection_user");
			//Connect c = new Connect();
			if(con==null)
			{con = connection();
			session.setAttribute("connection_user",con);
			//System.out.println("first time");
			}

			stmt = con.createStatement();
			result = stmt.executeQuery(query);
			// if(result.next()){
			// System.out.println(result.getString(1));

			// }

		
		
		return result;
	}
	public Connection getConnetion() throws Exception
	{
		Connection con = null;
		try
		{
			HttpSession session=ServletActionContext.getRequest().getSession();
			con=(Connection)session.getAttribute("connection_user");
			//Connect c = new Connect();
			if(con==null)
			{
				con = connection();
				session.setAttribute("connection_user",con);
				return con;
				//System.out.println("first time");
			}

			
			//PreparedStatement ps = con.prepareStatement(query);
			//ps.executeUpdate();
		}
		catch (Exception e)
		{
			throw new Exception(e);
			//e.printStackTrace();
		}
		return con;
	}
	public void dml(String query) throws Exception
	{
		// System.out.println(query);
		Connection con = null;
		try
		{
			HttpSession session=ServletActionContext.getRequest().getSession();
			con=(Connection)session.getAttribute("connection_user");
			//Connect c = new Connect();
			if(con==null)
			{
				con = connection();
				session.setAttribute("connection_user",con);
				//System.out.println("first time");
			}


		    ps = con.prepareStatement(query);
			ps.executeUpdate();
		}
		catch (Exception e)
		{
			throw new Exception(e);
			//e.printStackTrace();
		}

	}
	
}
